﻿using Gx.Common;
using Gx.Common.Core;
using Gx.Dal;
using Gx.Dal.Manage;
using Gx.Dal.Shared;
using Gx.Model;
using Gx.Model.Entity;
using Gx.Model.Enums;
using Gx.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Web.UI.WebControls;


namespace Gx.Bll.Manage
{
    public class LKWarehouseContractBll
    {

        protected LKWarehouseContractDal dal = new LKWarehouseContractDal();
        protected LKIncidentalsDal lKIncidentalsDal = new LKIncidentalsDal();
        protected BaseDal<LKWarehouseContractDetail> lKWarehouseContractDetailDal = new BaseDal<LKWarehouseContractDetail>();
        protected LKAttachmentBll attachmentBll = new LKAttachmentBll();

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedList<LKWarehouseContract> GetLKWarehouseContractPageList(LKWarehouseContractInput input)
        {
            return dal.GetLKWarehouseContractPageList(input);
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public List<LKWarehouseContract> GetLKWarehouseContracts()
        {
            return dal.GetAll().ToList();
        }

        /// <summary>
        /// 新增包仓合同
        /// </summary>
        /// <param name="lKWarehouseContract"></param>
        /// <returns></returns>
        public ReturnModel AddLKWarehouseContract(LKWarehouseContractDto contract)
        {
            var lKWarehouseContract = contract.Bill;
            var costList = contract.CostList;
            //合同编号规则：L240520002
            //L+年月日+三位流水号
            string maxCode = dal.GetMaxLKWarehouseContractCode();
            string code = "B" + DateTime.Now.ToString("yyMMdd") + "001";
            if (!string.IsNullOrWhiteSpace(maxCode))
            {
                var maxMonth = maxCode.Substring(2, 2);
                var nowMonth = DateTime.Now.ToString("MM");
                if (maxMonth == nowMonth)
                {
                    int num = Convert.ToInt32(maxCode);//Convert.ToInt32(maxCode.Substring(7, 3));
                    num++;
                    code = "B" + num.ToString();//DateTime.Now.ToString("yyMMdd") + num.ToString().PadLeft(3, '0');
                }
                
            }

            lKWarehouseContract.ContractNo = code;

            lKWarehouseContract.IsValid = true;
            lKWarehouseContract.CreateTime = DateTime.Now;
            lKWarehouseContract.CreateUserId = LoginHelper.GetUserId();
            lKWarehouseContract.CreateUser = LoginHelper.UserName();
            lKWarehouseContract.CompanyId = UserContext.CompanyId;
            //var result = dal.Insert(lKWarehouseContract);

            if (costList != null && costList.Any())
            {
                costList.ForEach(item =>
                {
                    //item.ContractId = lKWarehouseContract.Id;
                    item.ContractNo = code;
                    item.ContractType = (int)BillType.WarehouseContract;
                    item.CreateUser = LoginHelper.UserName();
                    item.CreateUserId = LoginHelper.GetUserId();
                });
                //lKIncidentalsDal.Insert(costList);
            }
            //var detailList = contract.DetailList;
            //if (detailList != null && detailList.Any())
            //{
            //    detailList.ForEach(item =>
            //    {
            //        item.ContractId = lKWarehouseContract.Id;
            //        item.CreateTime = DateTime.Now;
            //    });
            //    lKWarehouseContractDetailDal.Insert(detailList);
            //}

            var result = dal.AddLKWarehouseContract(lKWarehouseContract, costList, contract.DetailList);

            if (result && contract.AttachmentId > 0)
            {
                attachmentBll.SaveLKAttachment(new LKAttachment
                {
                    Id = contract.AttachmentId,
                    BillNo = lKWarehouseContract.ContractNo,
                    BillType = (int)BillTypeTemplate.Warehouse,
                });
            }

            return new ReturnModel { Success = result, Msg = result ? "新增成功" : "新增失败" };
        }

        /// <summary>
        /// 编辑包仓合同
        /// </summary>
        /// <param name="lKWarehouseContract"></param>
        /// <returns></returns>
        public bool EditLKWarehouseContract(LKWarehouseContractDto contractDto)
        {
            var lKWarehouseContract = contractDto.Bill;
            var cus = dal.Get(lKWarehouseContract.Id);
            if (cus == null)
            {
                return false;
            }
            if (cus.CompanyId != UserContext.CompanyId) return false;

            lKWarehouseContract.CreateTime = cus.CreateTime;
            lKWarehouseContract.CreateUserId = cus.CreateUserId;
            lKWarehouseContract.CreateUser = cus.CreateUser;
            lKWarehouseContract.ModifyUserId = LoginHelper.GetUserId();
            lKWarehouseContract.ModifyUser = LoginHelper.UserName();
            lKWarehouseContract.ModifyTime = DateTime.Now;
            lKWarehouseContract.CompanyId = UserContext.CompanyId;


            var result = dal.EditLKWarehouseContract(lKWarehouseContract, contractDto.CostList, contractDto.DetailList);

            if (result && contractDto.AttachmentId > 0)
            {
                attachmentBll.DeleteLKAttachment(lKWarehouseContract.ContractNo);
                attachmentBll.SaveLKAttachment(new LKAttachment
                {
                    Id = contractDto.AttachmentId,
                    BillNo = lKWarehouseContract.ContractNo,
                    BillType = (int)BillTypeTemplate.ZeroWarehouse,
                });
            }
            return result;


            //var result = dal.Update(lKWarehouseContract);
            //var costList = contractDto.CostList;
            //if (costList != null && costList.Any())
            //{
            //    var adds = costList.Where(c => c.Id == 0).ToList();
            //    var updates = costList.Where(c => c.Id > 0).ToList();


            //    if (updates.Any())
            //    {
            //        lKIncidentalsDal.Update(updates);

            //        var upids = updates.Select(s => s.Id);
            //        var deletes = lKIncidentalsDal.GetListByWhere("Id Not IN @ids", new { ids = upids }).Select(s => s.Id);
            //        if (deletes.Any())
            //        {
            //            lKIncidentalsDal.DeleteByIds(deletes.ToList());
            //        }
            //    }
            //    if (adds.Any())
            //    {
            //        adds.ForEach(item =>
            //        {
            //            item.ContractId = lKWarehouseContract.Id;
            //            item.ContractType = (int)BillType.WarehouseContract;
            //            item.CreateUser = LoginHelper.UserName();
            //            item.CreateUserId = LoginHelper.GetUserId();
            //        });
            //        lKIncidentalsDal.Insert(adds);
            //    }

            //}

            //var detailList = contractDto.DetailList;
            //if (detailList != null && detailList.Any())
            //{
            //    var adds = detailList.Where(c => c.Id == 0).ToList();
            //    var updates = detailList.Where(c => c.Id > 0).ToList();


            //    if (updates.Any())
            //    {
            //        lKWarehouseContractDetailDal.Update(updates);

            //        var upids = updates.Select(s => s.Id);
            //        var deletes = lKWarehouseContractDetailDal.GetListByWhere("Id Not IN @ids", new { ids = upids }).Select(s => s.Id);
            //        if (deletes.Any())
            //        {
            //            lKWarehouseContractDetailDal.DeleteByIds(deletes.ToList());
            //        }
            //    }
            //    if (adds.Any())
            //    {
            //        adds.ForEach(item =>
            //        {
            //            item.ContractId = lKWarehouseContract.Id;
            //            item.CreateTime = DateTime.Now;
            //        });
            //        lKWarehouseContractDetailDal.Insert(adds);
            //    }

            //}

            //return result;
        }

        /// <summary>
        /// 删除包仓合同
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnModel DeleteLKWarehouseContract(int id)
        {
            LKWarehouseEntryDal lKWarehouseEntryDal = new LKWarehouseEntryDal();
            var contract = dal.Get(id);
            if (contract == null) return new ReturnModel { Success = false, Msg = "合同不存在" };
            if (contract.CompanyId != UserContext.CompanyId) return new ReturnModel { Success = false, Msg = "无权限" };
            var entry = lKWarehouseEntryDal.GetListByWhere("ContractNo=@ContractNo", new { contract.ContractNo }).ToList();
            if (entry.Any())
            {
                return new ReturnModel { Success = false, Msg = "该合同已有入库单，不能删除" };
            }

            var result= dal.DeleteLKWarehouseContract(id);//.DeleteById(id);
            if (result)
            {
                attachmentBll.DeleteLKAttachment(contract.ContractNo);
            }
            return new ReturnModel { Success = result, Msg = result ? "删除成功" : "删除失败" };
        }

        /// <summary>
        /// 获取包仓合同
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public LKWarehouseContractDto GetLKWarehouseContractById(int id)
        {
            var bill = dal.Get(id);

            if (bill.CompanyId != UserContext.CompanyId)
                return new LKWarehouseContractDto();

            var costList = lKIncidentalsDal.GetLKIncidentalsListByContract(id, (int)BillType.WarehouseContract);
            var details = lKWarehouseContractDetailDal.GetListByWhere("ContractId=@ContractId", new { ContractId = id }).ToList();

            var attachment = attachmentBll.GetLKAttachmentView(bill.ContractNo);
            return new LKWarehouseContractDto { Bill = bill, DetailList = details, CostList = costList, FilePath = attachment?.AttachmentName, FileName = attachment?.OriginalName };
        }
        /// <summary>
        /// 获取包仓合同明细
        /// </summary>
        /// <param name="contractId"></param>
        /// <returns></returns>
        public List<LKWarehouseContractDetail> GetKWarehouseContractDetail(int contractId) 
        {
            var details= lKWarehouseContractDetailDal.GetListByWhere("ContractId=@ContractId", new { ContractId = contractId }).ToList();
            return details;
        }

        /// <summary>
        /// 计算合同总金额，并返回列表
        /// </summary>
        /// <param name="detailView"></param>
        /// <returns></returns>
        public List<LKWarehouseContractDetail> GetLKWarehouseContractTotalAmount(DetailListView detailView)
        {
            var details = lKWarehouseContractDetailDal.GetListByWhere("ContractId=@ContractId", new { ContractId = detailView.ContractId }).ToList() ?? new List<LKWarehouseContractDetail>();
            if (detailView.LKWarehouseContractDetail != null)
            {
                //获取list里最大的EndTime
                var max = details.Max(l => l.EndTime);
                //max加一天
                max = max.AddDays(1);
                //按自然月计算，一个月按30天计算，1，用单价（月）除以30天得到单价，2,计算天数，用结束时间减去开始时间，3,用单价乘以数量乘以天数得到总金额
                //if (detailView.StoreAlgorithm != 3)
                //{
                //    detailView.LKWarehouseContractDetail.UnitPrice = detailView.LKWarehouseContractDetail.UnitPrice / 30;
                //}
                var days = detailView.LKWarehouseContractDetail.EndTime.Subtract(max).Days + 1;
                var totalAmount = detailView.LKWarehouseContractDetail.UnitPrice * detailView.LKWarehouseContractDetail.Number * days;
                detailView.LKWarehouseContractDetail.TotalPrice = Math.Round(totalAmount, 2);

                //按自然天计算，1,用单价乘以数量乘以天数得到总金额


                detailView.LKWarehouseContractDetail.BeginTime = max;
                details.Add(detailView.LKWarehouseContractDetail);
            }

            return details;
        }


        /// <summary>
        /// 通过客户id获取合同
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public List<ContractDto> GetContractByCustomerId(int customerId)
        {
            return dal.GetContractListByCustomerId(customerId);
        }

        /// <summary>
        /// 通过客户id获取零仓合同
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public List<ContractDto> GetZeroContractByCustomerId()
        {
            return dal.GetZeroContractListByCustomerId();
        }
    }
}

